<template>
	<view class="login-tel">
		<view class="tel-main">
			<view class="login-from">
				<view class="login-user">
					<text class="user-name">验证码：</text>
					<input type="text" focus="true" placeholder="请输入验证码" v-model="userCode" />
					<button @click="sendCode" class="btn" plain="true" :disabled="disabled" size="mini">{{codeMsg}}</button>
				</view>
			</view>
			<view class="tel" @tap="goIndex">下一步</view>
		</view>
	</view>
</template>

<script>
	import $http from '../../common/api/request.js'
	import Lines from '@/components/common/Lines.vue'
	export default {
		data() {
			return {
				//倒计时间
				codeNum:60,
				// 显示文本
				codeMsg:"",
				// 按钮是否禁用
				disabled:false,
				//用户的验证码
				userCode:"",
				//注册的手机号
				phone,
				//得到的验证码
				getCode
			}
		},
		components:{
			Lines
		},
		onLoad(e) {
			// console.log(e);
			this.phone = e;
			// this.getCode = '1234';
		},
		onReady() {
			this.codeMsg = '重新发送('+this.codeNum+')';
			this.sendCode();
		},
		methods: {
			// 点击验证码发送
			sendCode() {
				//请求验证码
				$http.request({
					url:"/code",
					method:"POST",
					data:{
						userName:this.phone,
					}
				}).then((res)=>{
					// console.log(res);
					this.getCode = res.code;
				}).catch(()=>{
					uni.showToast({
						title:'请求失败',
						icon:'none'
					})
				})
				this.disabled = true;
				let timer = setInterval(()=>{
					--this.codeNum;
					this.codeMsg = '重新发送('+this.codeNum+')';
				},1000);
				setTimeout(()=>{
					// 十秒后清除倒计时
					clearInterval(timer);
					this.codeNum = 60;
					this.disabled = false;
					this.codeMsg = '重新发送';
				},60000)
			},
			// 点击下一步
			goIndex(){
				//判断写入的验证码和发送的验证码是否一致
				if( this.getCode == this.userCode){
					//请求接口，往数据库增加一条数据
					$http.request({
						url:"/addUser",
						method:"POST",
						data:{
							userName:this.phone,
							code:this.userCode //用户输入的验证码
						}
					}).then((res)=>{
						//注册成功
						if(res.success){
							uni.showToast({
								title:res.msg,
								icon:"none"
							})
							uni.redirectTo({
								url:'../index/index'
							})
						}
						
					}).catch(()=>{
						uni.showToast({
							title:'请求失败',
							icon:'none'
						})
					})
				}else{
					uni.showToast({
						title:'验证码错误',
						icon:'none'
					})
				}
			}
		}
	}
</script>

<style scoped>
.login-tel {
	width: 100vw;
	height: 100vh;
}
.tel-main {
	padding: 0 20rpx;
}

.login-from {
	padding-top: 20rpx;
}

.login-user {
	font-size: 32rpx;
	padding: 20rpx 0;
	display: flex;
	align-items: center;
	border-bottom: 2rpx solid #CCCCCC;
}
.user-name {
	padding-right: 5rpx;
}
.reminder {
	color: #636263;
	font-size: 32rpx;
	padding: 20rpx 0;
	text-align: center;
}
.tel {
	margin-top: 20rpx;
	width: 100%;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	color: #FFFFFF;
	background-color: #49BDFB;
	border-radius: 40rpx;
}
/* 按钮 */
.btn {
	border-radius: 40rpx;
	line-height: 60rpx;
}
</style>
